package cn.xy.org.controller;

import cn.xy.basic.util.AjaxResult;
import cn.xy.basic.util.PageList;
import cn.xy.org.domain.Employee;
import cn.xy.org.query.EmployeeQuery;
import cn.xy.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制层
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 查所有
     * @return
     */
    @GetMapping
    public List<Employee> queryAll(){
        return employeeService.findAll();

    }
    /**
     * 按id查询
     */
    @GetMapping("/{id}")
    public Employee queryById(Long id){
        return employeeService.findById(id);
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(Long id){
        try {
            employeeService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

    /**
     * 新增或修改
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if(employee.getId()==null){
                //为空则新增
                employeeService.save(employee);
            }else {
                //为修改
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /**
     * 分页与高级查询
     */
    @PostMapping
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery query){
        //返回业务层查询到的总数据，包括总条数和当前页面数据
        return employeeService.queryPage(query);
    }

    /**
     * 批量删除
     */
    @PatchMapping
    public AjaxResult batchRemove(@RequestBody List<Long> ids){
        try {
            employeeService.batchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }










}
